package process;

import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * @author huangy
 * @since 2022/8/17 11:39 上午
 */
public class TypeCounter extends HashMap<Class<?>, Integer> {

    //基础类型
    private final Class<?> baseType;

    public TypeCounter(Class<?> baseType) {
        this.baseType = baseType;
    }

    public void count(Object obj) {
        Class<?> type = obj.getClass();
        if (!baseType.isAssignableFrom(type)) {
            System.out.println("类型不正确，无法进行计数");
        }
        countClass(type);
    }

    public void countClass(Class<?> type) {
        Integer quantity = get(type);
        //对类型进行计数
        put(type, quantity == null ? 1 : quantity + 1);
        Class<?> superType = type.getSuperclass();
        if (superType != null && baseType.isAssignableFrom(superType)) {
            countClass(superType);
        }
    }

    @Override
    public String toString() {
        String result = entrySet().stream().map(pair ->
                String.format("%s=%s", pair.getKey().getSimpleName(), pair.getValue()))
                .collect(Collectors.joining(", "));
        return "{" + result + "}";
    }

}
